package com.nuts.core.tool.service.impl;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import com.nuts.core.tool.service.IRedisService;

import lombok.extern.slf4j.Slf4j;

/**
 * redis 操作实现类
 * 
 * @author 许自辉
 * @date 2017年7月20日 上午9:12:38
 */
@Component
@Slf4j
public class RedisImpl implements IRedisService {
	/**
	 * https://www.jianshu.com/p/7bf5dc61ca06 redisTemplate.opsForValue();//操作字符串
	 * redisTemplate.opsForHash();//操作hash redisTemplate.opsForList();//操作list
	 * redisTemplate.opsForSet();//操作set redisTemplate.opsForZSet();//操作有序set
	 */

	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	//private RedisTemplate<String, Object> redisTemplate;

	/**
	 * 设置缓存
	 */
	@Override
	public void set(String key, String value) {
		stringRedisTemplate.opsForValue().set(key, value);
		log.info("Redis set success - " + key + ", value:" + value);
	}

	/**
	 * 设置缓存 并同时设置有效期
	 * 
	 * @param seconds
	 *            以秒为单位
	 */
	@Override
	public void setex(String key, int seconds, String value) {
		stringRedisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
	}

	/**
	 * 获取缓存
	 */
	@Override
	public String get(String key) {
		String result = stringRedisTemplate.opsForValue().get(key);
		log.info("Redis get success - " + key + ", value:" + result);
		return result;
	}

	/**
	 * 删除缓存信息
	 * 
	 * @return 是否删除成功
	 */
	@Override
	public boolean del(String key) {
		boolean deleteFlag = stringRedisTemplate.delete(key);
		log.info("Redis delete key  success - " + key);

		return deleteFlag;
	}

}
